<?php

class AccountService extends BaseService
{
    private static $self = NULL;
    private $userInfo = NULL;

    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }

        return self::$self;
    }


    private $mSupplier    = NULL;



    public function __construct()
    {
        $this->mSupplier          = new Involved_SupplierModel();
    }

    /**
     * 表单验证
     * @param $obj
     * @param $arr
     * @author alice
     * @date 2016-1-19
     * @return bool
     */
    public function  checkProperties($obj, $arr)
    {
        if(empty($arr)) return true;
        $obj    =   (array) $obj;

        foreach($arr as $v){
            if(empty($obj[$v])){
                return false;}
        }
        return true;
    }

    /**
     * 商家列表
     * @author alice
     * @date 2016-1-19
     * @return mixed
     */
    public function ShowSupplierList()
    {
        return $this->mSupplier->ShowSupplierList();
    }

    /**
     * 商家详情
     * @param $id
     * @author alice
     * @date 2016-1-19
     * @return mixed
     */
    public function ShowSupplierInfo($id)
    {
        return $this->mSupplier->ShowSupplierInfo($id);
    }

    /**
     * 商家入驻
     * @param $paramObj
     * @author alice
     * @date 2016-1-19
     * @return int
     * @throws Exception
     */
    public function AddSupplier($paramObj)
    {
        #参数验证
        $check = $this->checkProperties($paramObj, ['corporation']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if(!empty($paramObj->supplier_img1))
        {
            #上传图片处理
            $file = $paramObj->supplier_img1;
            $clientName = $file->getClientOriginalName();
            $extension  = $file->getClientOriginalExtension();
            $newName    = md5(date('ymdhis') . $clientName) . "." . $extension;
            $file->move(public_path() . '/resource/upload', $newName);

            #生成缩略图
            ThumbnailService::instance()->setImageSize(375, 275);
            $image = file_get_contents(public_path() . '/resource/upload/' . $newName);
            ThumbnailService::instance()->loadData($image, 'image/jpeg');
            ThumbnailService::instance()->buildThumb(public_path() . '/resource/upload/thumb_' . $newName);

            $aData['supplier_img1'] = '/resource/upload/' . $newName;
        }

        #商家注入
        $aData = [
            'company'                =>     $paramObj->company,
            'supplier_name'          =>     $paramObj->supplier_name,
            'brand_name'             =>     $paramObj->brand_name,
            'place'                  =>     $paramObj->place,
            'market'                 =>     $paramObj->market,
            'scale'                  =>     $paramObj->scale,
            'business_scope'         =>     $paramObj->business_scope,
            'owner'                  =>     $paramObj->owner,
            'phone'                  =>     $paramObj->phone,
            'operate_license'        =>     $paramObj->operate_license,
            'tex_license'            =>     $paramObj->tex_license,
            'created'                =>     time()
        ];

        return $this->mSupplier->insert($aData);

    }

    /**
     * 修改商家资料
     * @param $paramObj
     * @author alice
     * @date 2016-1-19
     * @return bool
     * @throws Exception
     */
    public function EditSupplier($paramObj)
    {
        if(!empty($paramObj->supplier_img1))
        {
            #上传图片处理
            $file = $paramObj->supplier_img1;
            $clientName = $file->getClientOriginalName();
            $extension  = $file->getClientOriginalExtension();
            $newName    = md5(date('ymdhis') . $clientName) . "." . $extension;
            $file->move(public_path() . '/resource/upload', $newName);

            #生成缩略图
            ThumbnailService::instance()->setImageSize(375, 275);
            $image = file_get_contents(public_path() . '/resource/upload/' . $newName);
            ThumbnailService::instance()->loadData($image, 'image/jpeg');
            ThumbnailService::instance()->buildThumb(public_path() . '/resource/upload/thumb_' . $newName);

            $aData['supplier_img1'] = '/resource/upload/' . $newName;
        }

        $aData = [
            'company'                =>     $paramObj->company,
            'supplier_name'          =>     $paramObj->supplier_name,
            'brand_name'             =>     $paramObj->brand_name,
            'place'                  =>     $paramObj->place,
            'market'                 =>     $paramObj->market,
            'scale'                  =>     $paramObj->scale,
            'business_scope'         =>     $paramObj->business_scope,
            'owner'                  =>     $paramObj->owner,
            'phone'                  =>     $paramObj->phone,
            'operate_license'        =>     $paramObj->operate_license,
            'tex_license'            =>     $paramObj->tex_license,
            'created'                =>     time()
        ];

        return $this->mSupplier->update($aData,['supplier_id'=>$paramObj->supplier_id]);

    }

    /**
     * 删除商家
     * @param $supplier_id
     * @author alice
     * @date 2016-1-19
     * @return int
     */
    public function DeleteSupplierInfo($supplier_id){

        return $this->mSupplier->delete(['supplier_id'=>$supplier_id]);
    }








    public function setRequestStuffParams($aParams)
    {
        $this->oStuffInfo = VO_Bound::Bound($aParams, new VO_Request_DimStuff());
        return $this->oStuffInfo;
    }

    public function setResponseStuffParams($aParams)
    {
        $this->oStuffInfoOld = VO_Bound::Bound($aParams, new VO_Response_DimStuff());
        return $this->oStuffInfoOld;
    }


    /**
     * 验证用户
     * @param $user
     * @return bool|VO_Common|VO_Response_DimStuff
     * @throws Exception
     */
    public function LoginValidator($user)
    {
        #此处只做简单验证
        if(empty($user->user_name) || empty($user->user_pwd) || empty($user->captcha)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if(strtolower($user->captcha) != strtolower(Session::get('UdoCaptcha'))){
            throw new Exception('验证码错误', ProfessionErrorCodeEnum::ERROR_VERIFICATION_CODE_WRONG);
        }

        #数据验证
        $this->mStuffInfo->setSelect(array('stuff_id','stuff_name','stuff_code','role_id','mobile','salt','password'));
        $get_info = $this->mStuffInfo->fetchRow(array('mobile' => $user->user_name));

        if($get_info){
            if ($get_info->password != md5(md5($user->user_pwd.$get_info->salt))) {
                throw new Exception('密码错误', ProfessionErrorCodeEnum::ERROR_PASSWORD_WRONG);
            }
            unset($get_info->password);
            unset($get_info->salt);

            Session::put(UserEnum::USER_INFO_SESSION_KEY, $get_info);
        }else{
            throw new Exception('用户名错误', ProfessionErrorCodeEnum::ERROR_ACCOUNT_NOT_EXIST);
        }

    }


    /**
     * 获得默认登录页
     * @param $role_id
     * @return string
     */
    public function getDefaultPage($role_id)
    {
        switch($role_id)
        {
            case AdminEnum::SUPPER_ADMIN_ROLE:
                //林场管理
                $page =  '/forest_service';
                break;
            case AdminEnum::GENERAL_ADMIN_ROLE:
                //林场管理
                $page =  '/forest_service';
                break;
            case AdminEnum::EDITOR_ROLE:
                //林场管理
                $page =  '/forest_import';
                break;
            default:
                //返回登录
                $page =  '/';
                break;
        }
        return $page;
    }

    /**
     * 获取顶部日期
     * @return string
     */
    public function getBannerDate()
    {
        $week = array('日','一','二','三','四','五','六');
        return date('Y')."年".date('m')."月".date('d')."日 星期".$week[date('w')];
    }

    /**
     * 返回Session用户信息
     * @return mixed
     */
    public function getAccountInfo()
    {
        $user_info = Session::get(UserEnum::USER_INFO_SESSION_KEY);
        return $user_info;
    }

    /**
     * 返回用户信息
     * @return mixed
     */
    public function getAccountById($user_id)
    {
        return $this->mStuffInfo->fetchRow($user_id);
    }

    /**
     * 返回用户ID
     * @return mixed
     */
    public function getAccountId()
    {
        $user_info = Session::get(UserEnum::USER_INFO_SESSION_KEY);

        return $user_info->stuff_id;
    }

    public function getAccountRole()
    {
        $user_info = Session::get(UserEnum::USER_INFO_SESSION_KEY);

        return $user_info->role_id;
    }

    public function getUserName()
    {

        if(Session::has(UserEnum::USER_INFO_SESSION_KEY)){
            $this->userInfo = Session::get(UserEnum::USER_INFO_SESSION_KEY);
            return $this->userInfo->stuff_name;
        }

        return null;
    }

    /**
     * 获取一个用户信息
     * @param $user_id
     * @return array
     */
    public function getStuffInfo($user_id)
    {
        return $this->mStuffInfo->fetchRow($user_id);
    }

    /**
     * 读取人员信息
     * @param $role
     * @param $page
     * @return array
     */
    public function getAccountByRole($role, $page)
    {
        $cacheKey = 'getAccountByRole_role('. $role . ')_page(' . $page . ')';
        if($this->redis->exists($cacheKey)){
            return $this->redis->get($cacheKey);
        }else{
            $aWhere = array('role_id' => $role );
            $num = 20*($page-1);
            $this->mStuffInfo->setLimit($num,20);
            $result = $this->mStuffInfo->fetchAll($aWhere, array(), array('stuff_code'=>'asc'));

            if($role == UserEnum::USER_ROLE_TEACHER)
            {
                foreach($result as &$teacher)
                {
                    $teacher->subject_name = $this->getTeacherInfo($teacher);
                    $teacher->is_provost   = $this->checkTeacherProvost($teacher);
                }
            } elseif ($role == UserEnum::USER_ROLE_LEADER) {

                foreach($result as &$teacher)
                {
                    $provost_info = $this->getProvostByLeaderId($teacher->stuff_id);
                    $teacher->provost = $provost_info;
                }
            }
            $this->redis->set($cacheKey, $result, 60);
            return $result;
        }
    }

    private function getProvostByLeaderId($leader_id)
    {
        $provost_info = $this->mProvostGroupInfo->fetchRow(array('leader_id' => $leader_id));
        if (!empty($provost_info)) {
            $teacher_list = DB::table('provost_teacher')
                ->select('stuff_name as teacher_name', 'provost_teacher.teacher_id')
                ->leftJoin('stuff', 'stuff.stuff_id', '=', 'provost_teacher.teacher_id')
                ->where('group_id', $provost_info->group_id)
                ->get();
            $provost_info->teacher_list = array();
            foreach ($teacher_list as $v) {
                $provost_info->teacher_list[] = $v;
            }
        }

        return $provost_info;
    }

    public function checkTeacherProvost($teacher)
    {
        $count =  $this->mProvostGroupInfo->count(array('leader_id' => $teacher->stuff_id));
        return ($count > 0) ? "教务组长" : "普通教师";
    }



    public function getTeacherInfo($teacher)
    {
        $subject_name = array();
        $subjects = $this->mTeacherSubject->fetchAll(array('teacher_id' => $teacher->stuff_id));
        if($subjects){
            foreach($subjects as &$subject){
                $subject_name[] =  $subject->subject_name;
            }
            $subject_name = implode(",",$subject_name);
        }else{
            $subject_name = "";
        }

        return $subject_name;
    }

    public function getStuffNumberByRole($role)
    {
        $cacheKey = 'getStuffNumberByRole_role('. $role . ')';
        if($this->redis->exists($cacheKey)){
            return $this->redis->get($cacheKey);
        }else{
            $result = $this->mStuffInfo->count(array('role_id' => $role ));
            $this->redis->set($cacheKey, $result, 60);
            return $result;
        }

    }

    /**
     * 校验用户名 密码 获取用户信息
     * @param $phone
     * @param $password
     * @return array
     * @throws Exception
     */
    public function validAccount($phone, $password = null)
    {
        #数据验证
        $error_msg = ProfessionErrorCodeEnum::$status_msgs;
        $user_info = $this->mStuffInfo->fetchRow(array('mobile' => $phone));
        if ($user_info) {   //用户未找到
            $error_code = ProfessionErrorCodeEnum::ERROR_ACCOUNT_NOT_EXIST;
            throw new Exception($error_msg[$error_code], $error_code);
        }
        if (!is_null($password)) {
            if ($user_info->password == '') {   //用户未设置密码
                $error_code = ProfessionErrorCodeEnum::ERROR_USER_PASSWORD_NULL;
                throw new Exception($error_msg[$error_code], $error_code);
            }
            $password = $this->getPassword($password, $user_info->salt);

            if ($password != $user_info->password) {    //密码不正确
                $error_code = ProfessionErrorCodeEnum::ERROR_PASSWORD_WRONG;
                throw new Exception($error_msg[$error_code], $error_code);
            }
        }

        return $user_info;
    }

    /**
     * 设置密码，重置密码
     * @param $user_info
     * @param $new_password
     * @throws Exception
     */
    public function resetPassword($user_info, $new_password)
    {
        $new_password = $this->getPassword($new_password, $user_info->salt);
        $result = $this->mStuffInfo->update(
                array('password' => $new_password),
                array('mobile' => $user_info->mobile)
            );
        if (!$result) {
            $error_msg = ProfessionErrorCodeEnum::$status_msgs;
            $error_code = ProfessionErrorCodeEnum::ERROR_PASSWORD_SET_FAIL;
            throw new Exception($error_msg[$error_code], $error_code);
        }
    }

    /**
     * 修改密码
     * @param $user_info
     * @param $new_password
     * @param $old_password
     * @throws Exception
     */
    public function setNewPassword($user_info, $new_password, $old_password)
    {
        $error_msg = ProfessionErrorCodeEnum::$status_msgs;
        $old_password = $this->getPassword($old_password, $user_info->salt);

        if ($user_info->password != $old_password) {
            $error_code = ProfessionErrorCodeEnum::ERROR_PASSWORD_ORIGINAL_WRONG;
            throw new Exception($error_msg[$error_code], $error_code);
        }

        $new_password = $this->getPassword($new_password, $user_info->salt);
        $result = $this->mStuffInfo->update(array('password' => $new_password), array('mobile' => $phone));
        if (!$result) {
            $error_code = ProfessionErrorCodeEnum::ERROR_PASSWORD_RESET_FAIL;
            throw new Exception($error_msg[$error_code], $error_code);
        }
    }

    private function getPassword($password, $salt)
    {
        return md5(md5($password.$salt));
    }

    /**
     * 获取设备信息
     * @param $user_id
     * @return mixed
     */
    public function getDeviceInfo($user_id)
    {
        return $this->mDevice->fetchRow(array('user_id' => $user_id));
    }

    /**
     * 非正常情况退出时的注销
     */
	public function clearDevice($client_id, $os_type = NULL, $device = NULL, $token = NULL) {

        $aWhere = array(
            'client_id' => $client_id,
            'os_type'   => $os_type
        );
        $count = $this->mDevice->count($aWhere);
        if ($count){
//            $this->mDevice

            $sql = "UPDATE $this->_type_table SET token = '" . $token . "',clientid = '".NULL."',devicetoken = '".$device."' WHERE clientid = '".$client."'   AND type = '".$osType."'";
            return $this->update ( $sql );
        }
    }

    /**
     * 保存用户资料
     * @param $paramObj
     * @param $user_id
     * @throws Exception
     */
    public function savePerionDetail($paramObj, $user_id)
    {
        if (is_array($paramObj)) {
            $paramObj = (array)$paramObj;
        }
        $result = $this->mStuffInfo->update($paramObj, $user_id);
        if (!$result) {
            $error_msg  = ProfessionErrorCodeEnum::$status_msgs;
            $error_code = ProfessionErrorCodeEnum::ERROR_PERION_DETAIL_SAVE_WRONG;
            throw new Exception($error_msg[$error_code], $error_code);
        }
    }

    public function addStudentLeader($user_id,$student_ids)
    {
        $aData = array();
        foreach($student_ids as $key=>$student_id)
        {
            if(!$is_have = $this->mContactStudent->checkStudent($user_id, $student_id))
            {
                $aData[] = array(
                    'contact_id' => $user_id,
                    'student_id' => $student_id
                );
            }
        }
        return $this->mContactStudent->insert($aData);
    }

    public function getStudentList($keyword)
    {
        if($keyword){
            return DB::table('stuff')
                ->where('stuff_name', 'like', '%'.$keyword.'%')
                ->where('role_id',UserEnum::USER_ROLE_STUDENT)
                ->get();
        }else{
            return DB::table('stuff')
                ->where('role_id',UserEnum::USER_ROLE_STUDENT)
                ->get();
        }
    }

}


